package com.duck.duckchatbackend.websocket.netty;

import com.duck.duckchatbackend.entity.dto.TokenUserInfoDto;
import com.duck.duckchatbackend.redis.RedisComponent;

import com.duck.duckchatbackend.utils.StringTools;
import com.duck.duckchatbackend.websocket.ChannelContextUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;

@Component
@ChannelHandler.Sharable
public class HandlerWebSocket extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Resource
    private RedisComponent redisComponent;

    @Resource
    private ChannelContextUtils channelContextUtils;


    private static  final Logger logger = LoggerFactory.getLogger(HandlerWebSocket.class);

    /*
    * 通道就绪后调用，一般用来做初始化
    * */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
           logger.info("有新的连接加入...");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("有连接断开了...");
        channelContextUtils.removeContext(ctx.channel());
    }
    /*
    * 收消息
    * */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame textWebSocketFrame) throws Exception {
        Channel channel = ctx.channel();
        //logger.info("收到消息{}",textWebSocketFrame.text());
        //根据channel.id().toString()获取到AttributeKey，再根据AttributeKey获取到Attribute<String> attribute。然后获取到userId
        Attribute<String> attribute = channel.attr(AttributeKey.valueOf(channel.id().toString()));
        //获取userId
        String userId = attribute.get();
       // logger.info("收到消息userId{}的消息：{}",userId,textWebSocketFrame.text());
        redisComponent.saveUserHeartBeat(userId);
        //向群组发消息
        //channelContextUtils.send2Group(textWebSocketFrame.text());
    }
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        // 检查事件是否为WebSocket握手完成事件
        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete){
          // 将事件转换为HandshakeComplete对象
          WebSocketServerProtocolHandler.HandshakeComplete complete = (WebSocketServerProtocolHandler.HandshakeComplete) evt;
          // 获取握手请求的URI
          String url = complete.requestUri();
          String token = getToken(url);
          if(token == null){
              ctx.channel().close();
              return;
          }
          // 获取token对应的用户信息
          TokenUserInfoDto tokenUserInfoDto = redisComponent.getTokenUserInfoDto(token);
          // 判断用户信息是否为空, 为空则关闭连接
          if(null == tokenUserInfoDto){
              ctx.channel().close();
              return;
          }
          // 将用户id保存到channel的Attribute中
          channelContextUtils.addContext(tokenUserInfoDto.getUserId(), ctx.channel());
          // 记录请求的URI到日志
          logger.info("url {}",url);
        }
    }
    private String getToken(String url){
       if(StringTools.isEmpty(url) || url.indexOf("?") == -1){
           return null;
       }
       //用问号将字符串分割
       String[] queryParams = url.split("\\?");
       if(queryParams.length!=2){
          return  null;
       }
       //用等号将参数分割
       String[] params = queryParams[1].split("=");
       if(params.length!=2){
          return  null;
       }
       return  params[1];
    }
}
